package com.topvision.jack.uploadlibrary.utils;

import android.content.Context;
import android.content.Intent;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * 文件相关操作
 * 创建时间:2017/12/20
 * 作者 jack
 * 描述
 */
public class FileUtils {

    public static final String ACTION_MEDIA_SCANNER_SCAN_DIR = "android.intent.action.MEDIA_SCANNER_SCAN_DIR";

    /**
     * 创建目录
     *
     * @param context    上下文
     * @param folderPath 目录路径
     */
    public static File createFolder(Context context, String folderPath) {
        File folderFile = new File(folderPath);
        if (!folderFile.exists()) {
            folderFile.mkdirs();
            // fileScan(context, folderPath);
        }
        return folderFile;
    }

    public static boolean removeFile(Context context, String path) {
        File file = new File(path);
        if (file.exists()) {
            return file.delete();
            // fileScan(context, folderPath);
        }
        return false;
    }


    /**
     * 扫描 mtp下的文件，在保存文件到 sd卡下后，不能显示，故这里触发一下扫描机制，让手机连上电脑后，就可以读出文件了
     *
     * @param fName 文件路径
     *              create at 2017/2/7 9:22
     */
    public static void fileScan(Context context, String fName) {
        File file = new File(fName);
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
            if (file.isDirectory()) {
                scanDirAsync(context, fName);
            } else {
                Uri data = Uri.parse("file:///" + fName);
                context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, data));
            }

        } else {
            //异步扫描目录
            if (file.isDirectory()) {
                scanDirAsync(context, fName);
            } else {
                MediaScannerConnection.scanFile(context,
                        new String[]{fName}, null,
                        new MediaScannerConnection.OnScanCompletedListener() {
                            public void onScanCompleted(String path, Uri uri) {
                                Log.i("ExternalStorage", "Scanned " + path + ":");
                                Log.i("ExternalStorage", "-> uri=" + uri);
                            }
                        });
            }

        }

    }

    public static void scanDirAsync(Context ctx, String dir) {
        Intent scanIntent = new Intent(ACTION_MEDIA_SCANNER_SCAN_DIR);
        scanIntent.setData(Uri.fromFile(new File(dir)));
        ctx.sendBroadcast(scanIntent);
    }

    /**
     * 通过路径获取文件名称
     *
     * @param path
     * @return
     */
    public static String getFileName(String path) {
        if (TextUtils.isEmpty(path)) {
            return null;
        }
        int index = path.lastIndexOf("/");
        return path.substring(index + 1, path.length());
    }


    /**
     * 通过路径获取目录名称
     *
     * @param path
     * @return
     */
    public static String getFolderName(String path) {
        if (TextUtils.isEmpty(path)) {
            return null;
        }
        int index = path.lastIndexOf("/");
        return path.substring(0, index);
    }

    /**
     * 文件重命名
     * 创建时间:2017/12/22
     * 作者 jack
     * 描述
     */
    public static String renameFile(String outputPath) {
        File outputFile = new File(outputPath);
        //包含后缀名的视频文件名称
        String tempFileName = outputFile.getName();
        String fileName = tempFileName.split("\\.")[0];
        String ext = tempFileName.split("\\.")[1];
        //生成临时文件
        outputPath = outputPath.replace(tempFileName, fileName + "_" + System.currentTimeMillis() + "." + ext);
        File newFile = new File(outputPath);
        //文件重命名
        outputFile.renameTo(newFile);
        return newFile.getPath();
    }


    public static byte[] getBlock(long offset, File file, int blockSize) {
        byte[] result = new byte[blockSize];
        RandomAccessFile accessFile = null;
        try {
            accessFile = new RandomAccessFile(file, "r");
            accessFile.seek(offset);
            int readSize = accessFile.read(result);
            if (readSize == -1) {
                return null;
            } else if (readSize == blockSize) {
                return result;
            } else {
                byte[] tmpByte = new byte[readSize];
                System.arraycopy(result, 0, tmpByte, 0, readSize);
                return tmpByte;
            }


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (accessFile != null) {
                try {
                    accessFile.close();
                } catch (IOException e1) {
                }
            }
        }
        return null;
    }


}
